package cn.snow.iot.module.warning.event;

import cn.hutool.core.util.StrUtil;
import cn.snow.iot.module.message.api.send.SendApi;
import cn.snow.iot.module.message.api.send.dto.SendMessageRequestDto;
import cn.snow.iot.module.system.api.dict.dto.DictDataRespDTO;
import cn.snow.iot.module.warning.service.record.IWarningRecordService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.stereotype.Component;
import java.util.*;

/**
 * @author: chen_gang
 * @date: 2024/8/12 16:09
 * @description: 监听不同事件类型，执行对应业务逻辑
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class WarningEventHandler {

    private final IWarningRecordService warningRecordService;

    //消息服务发送接口
    private final SendApi sendApi;

    private final RedisCacheManager redisCacheManager;

    /**
     * mysql持久化事件监听器
     */
    @EventListener({MysqlWarningEvent.class})
    public void handleMysqlAction(MysqlWarningEvent event) {
        JSONObject data = event.getJsonObject();
        data.put("uuId", event.getUuId());
        warningRecordService.handleWarningRecord(data);
        log.info("mysql持久化动作处理成功，请求内容 {}", event);
    }

    /**
     * 消息发送事件监听器
     */
    @EventListener({MessageWarningEvent.class})
    public void handleMessageAction(MessageWarningEvent event) {
        //构造消息发送实体
        String params = event.getParams();
        JSONObject data = JSONObject.parseObject(params);
        Long templateId = data.getLong("templateId");
        Map<String, Object> innerMap = data.getInnerMap();
        String uuId = event.getUuId();
        Long actionId = event.getActionId();
        //消息服务仅支持单次单人发送模式，故在此循环发送消息
        Map<String, Object>  finalInnerMap = formatParam(innerMap,event);
        JSONArray userArray = data.getJSONArray("users");

        userArray.forEach(user -> {
            List<String> users = new ArrayList();
            users.add(user.toString());
            SendMessageRequestDto requestBody = new SendMessageRequestDto(
                    templateId,
                    users,
                    finalInnerMap,
                    uuId,
                    actionId,
                    0);
            //调用消息服务，进行消息发送
            sendApi.sendMessage(requestBody);
            log.info("消息发送动作处理成功，请求内容 uuID:{} actionId:{} user:{} templateId:{}", uuId, actionId, user, templateId);
        });
    }

    public Map<String, Object> formatParam(Map<String, Object> paramMap,MessageWarningEvent event){
        HashMap<String,String> platFormMap = new HashMap();
        platFormMap.put("platformName", "物联网");
        platFormMap.put("platformUrl", "");
        platFormMap.put("dateTime", "");
        platFormMap.put("deviceName", "");
        platFormMap.put("deviceCode", "");
        platFormMap.put("pointName", "");
        platFormMap.put("pointCode", "");
        platFormMap.put("pointValue", "");

        JSONObject templateParam = (JSONObject) paramMap.get("templateParam");
        Map<String, Object> templateParamMap = templateParam.getInnerMap();

        templateParamMap.entrySet().forEach(entry -> {
            //获取value值  并替换map原来值
            if ("dateTime".equals(entry.getValue())){
                templateParamMap.put(entry.getKey(),event.getJsonObject().get("thetime"));
            } else if ("deviceName".equals(entry.getValue())){
                templateParamMap.put(entry.getKey(),event.getWarningDetailVO().getEquipmentName());
            } else if  ("deviceCode".equals(entry.getValue())){
                templateParamMap.put(entry.getKey(),event.getWarningDetailVO().getEquipmentCode());
            } else if  ("pointName".equals(entry.getValue())){
                templateParamMap.put(entry.getKey(),event.getWarningDetailVO().getPointName());
            } else if  ("pointCode".equals(entry.getValue())){
                templateParamMap.put(entry.getKey(),event.getWarningDetailVO().getPointCode());
            } else if  ("pointValue".equals(entry.getValue())){
                templateParamMap.put(entry.getKey(),event.getJsonObject().get("value"));
            }else {
                String s = platFormMap.get(entry.getValue().toString());
                templateParamMap.put(entry.getKey(), s);
            }
        });
        String s = JSONObject.toJSONString(templateParamMap);
        switch (paramMap.get("channelType").toString()) {
            // 当动作是 站内信
            case "0" : {
                paramMap.put("templateParam",s);
                break;
            }
            default:
                break;
        }
        return paramMap;
    }
}
